import store from "../store";
import { TOKENNAME, HTTP_REQUEST_URL } from "../config/app.js";
import { shareToFriend } from "@/api/share";
import cache from "@/utils/cache";
// #ifdef H5
const jweixin = require("@/js_sdk/jweixin-module");
import wx from "@/js_sdk/jweixin-module";
// #endif


export default {
  /**
   * opt  object | string
   * to_url object | string
   * 例:
   * this.Tips('/pages/test/test'); 跳转不提示
   * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
   * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
   * tab=1 一定时间后跳转至 table上
   * tab=2 一定时间后跳转至非 table上
   * tab=3 一定时间后返回上页面
   * tab=4 关闭所有页面跳转至非table上
   * tab=5 关闭当前页面跳转至table上
   */
  Tips: function (opt, to_url) {
    if (typeof opt == "string") {
      to_url = opt;
      opt = {};
    }
    let title = opt.title || "",
      icon = opt.icon || "none",
      endtime = opt.endtime || 2000,
      success = opt.success;
    if (title)
      uni.showToast({
        title: title,
        icon: icon,
        duration: endtime,
        success,
      });
    if (to_url != undefined) {
      if (typeof to_url == "object") {
        let tab = to_url.tab || 1,
          url = to_url.url || "";
        switch (tab) {
          case 1:
            //一定时间后跳转至 table
            setTimeout(function () {
              uni.switchTab({
                url: url,
              });
            }, endtime);
            break;
          case 2:
            //跳转至非table页面
            setTimeout(function () {
              uni.navigateTo({
                url: url,
              });
            }, endtime);
            break;
          case 3:
            //返回上页面
            setTimeout(function () {
              // #ifndef H5 || APP-PLUS
              uni.navigateBack({
                delta: parseInt(url),
              });
              // #endif
              // #ifdef H5 || APP-PLUS
              history.back();
              // #endif
            }, endtime);
            break;
          case 4:
            //关闭当前所有页面跳转至非table页面
            setTimeout(function () {
              uni.reLaunch({
                url: url,
              });
            }, endtime);
            break;
          case 5:
            //关闭当前页面跳转至非table页面
            setTimeout(function () {
              uni.redirectTo({
                url: url,
              });
            }, endtime);
            break;
        }
      } else if (typeof to_url == "function") {
        setTimeout(function () {
          to_url && to_url();
        }, endtime);
      } else if (typeof to_url == "string") {
        uni.showToast({
          title: to_url,
          icon: "none",
        });
      } else {
        //没有提示时跳转不延迟
        setTimeout(
          function () {
            uni.navigateTo({
              url: to_url,
            });
          },
          title ? endtime : 0
        );
      }
    }
  },

  uploadImageAPi: function (opt, successCallback, errorCallback) {
    //启动上传等待中...
    uni.showLoading({
      title: "图片上传中",
    });
    let ImagePath = opt.path;
    let urlPath = `${HTTP_REQUEST_URL}/upload/image`;
    uni.hideLoading();
    // successCallback && successCallback(ImagePath)
    uni.uploadFile({
      url: urlPath,
      filePath: ImagePath,
      header: {
        // #ifdef MP || H5 || APP-PLUS
        "Content-Type": "multipart/form-data",
        // #endif
        // #ifdef H5 || APP-PLUS
        [TOKENNAME]: store.state.app.token,
        // #endif
        // #ifdef MP
        [TOKENNAME]: store.state.app.token_wx,
        // #endif
      },
      name: opt.name,
      formData: {
        type: opt.type,
      },
      success: function (res) {
        let data = res;
        uni.hideLoading();
        // todo
        if (res.statusCode === 200) {
          successCallback && successCallback(data);
        } else {
          errorCallback && errorCallback(data);
        }
      },
      fail: function (err) {
        console.log(err, "error");
        uni.hideLoading();
        errorCallback && errorCallback(err);
      },
    });
  },
  /*
   * 单图上传
   * @param object opt
   * @param callable successCallback 成功执行方法 data
   * @param callable errorCallback 失败执行方法
   */
  uploadImageOne: function (opt, successCallback, errorCallback) {
    let that = this;
    let count = opt.count || 1;
    let sizeType = opt.sizeType || ["compressed"];
    let sourceType = opt.sourceType || ["album", "camera"];
    uni.chooseImage({
      count,
      sizeType,
      sourceType,

      success: function (res) {
        uni.showLoading({
          title: "图片上传中",
        });
        let urlPath = `${HTTP_REQUEST_URL}/upload/image`;
        let localPath = res.tempFilePaths[0];
        // successCallback && successCallback(localPath)
        // return
        uni.uploadFile({
          url: urlPath,
          filePath: localPath,
          name: opt.name,
          formData: {
            type: opt.type,
          },
          header: {
            // #ifdef MP
            "Content-Type": "multipart/form-data",
            [TOKENNAME]: store.state.app.token_wx,
            // #endif
            // #ifdef H5 || APP-PLUS
            [TOKENNAME]: store.state.app.token,
            // #endif
          },
          success: function (res) {
            uni.hideLoading();
            //todo 处理逻辑
            successCallback && successCallback(res);
          },
          fail: function (res) {
            uni.hideLoading();
            console.log("上传失败");
          },
        });
      },
    });
  },

  transformData: function (jsonData, str = "") {
    let transformedData = [];
    // 遍历每一年的数据
    for (let i = 0; i < jsonData.length; i++) {
      let yearData = jsonData[i];
      let year = yearData.year;
      let monthData = yearData.monthData;

      for (let j = 0; j < monthData.length; j++) {
        let month;
        if (str == "F") {
          month = monthData[j].name; // 转换月份为带有月份后缀的形式
        } else {
          month =
            monthData[j].name == "合计"
              ? monthData[j].name
              : `${monthData[j].name}月`; // 转换月份为带有月份后缀的形式
        }

        let value = monthData[j].value ? parseFloat(monthData[j].value) : "-"; // 将值转换为浮点数
        let existingMonth = transformedData.find(
          (item) => item.month === month
        );

        if (existingMonth) {
          existingMonth[`price${i + 1}`] = `${value}`;
        } else {
          let newMonthEntry = {
            month: month,
            [`price${i + 1}`]: `${value}`,
          };
          transformedData.push(newMonthEntry);
        }
      }
    }

    return transformedData;
  },

  shareFriend() {
    shareToFriend({ url: location.origin + location.pathname }).then((res) => {
      if (res.code == 200) {
        this.setShare(res.data);
      }
    });
  },
  // 设置分享数据
  setShare(ticket, str, menuArr, hideArr = [], companyName = "") {
    cache.set("ticket", JSON.stringify(ticket));
    wx.config({
      debug: false, // 开启调试模式
      appId: ticket.appId, // 必填，公众号的唯一标识
      timestamp: ticket.timestamp, // 必填，生成签名的时间戳
      nonceStr: ticket.nonceStr, // 必填，生成签名的随机串
      signature: ticket.signature, // 必填，签名
      jsApiList: menuArr, // 必填，需要使用的JS接口列表
    });
    const strMap = {
      "H5-dev": "https://dev-manage.julimeng.com/2h5/",
      "H5-test": "https://test-manage.julimeng.com/2h5/",
      "H5-uat": "https://dev-manage.julimeng.com/2h5/",
      "H5-prod": "https://manage.shengdaiqifu.com/2h5/",
    };
    setTimeout(() => {
      wx.ready(function () {
        wx.checkJsApi({
          jsApiList: menuArr,
          success: function (res) {
            JSON.stringify(res);
          },
        });
        wx.hideMenuItems({
          menuList: ["menuItem:copyUrl", ...hideArr],
        });
        wx.updateAppMessageShareData({
          title: companyName == "" ? "助融报告" : companyName, // 分享标题
          desc:
            companyName == ""
              ? "一键支持用户免费自查税信息，用户授权后免费自查，生成报告，简单方便。"
              : "点击立即查看", // 分享描述
          link: str, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: strMap[process.env.ENV_TYPE] + "static/image/zhurongLogo.jpg", // 分享图标
          success: function () {
          },
        });

        wx.updateTimelineShareData({
          title: companyName == "" ? "助融报告" : companyName, // 分享标题
          link: str, // 分享链接
          imgUrl: strMap[process.env.ENV_TYPE] + "static/image/zhurongLogo.jpg", // 分享图标
          success: function () {
          },
        });
      });
    }, 500);
    wx.error(function (res) {
      // 分享失败处理逻辑
      console.error("微信分享失败:", res);
    });
  },

  /**
   *
   * 页面复制链接通用方法
   * @param {*} options 需要的参数
   * @param {*} url  页面回跳路由地址
   */
  getPageUrl: function (options, url) {
    const strMap = {
      "H5-dev": "https://dev-manage.julimeng.com/2h5/#/",
      "H5-test": "https://test-manage.julimeng.com/2h5/#/",
      "H5-uat": "https://dev-manage.julimeng.com/2h5/#/",
      "H5-prod": "https://manage.shengdaiqifu.com/2h5/#/",
    };
    let str = "";
    if (Object.keys(options).length > 0) {
      Object.keys(options).forEach((item) => {
        str += `${item}=${options[item]}&`;
      });
    }
    let urlPath = "";
    if (str == "") {
      urlPath = `${strMap[process.env.ENV_TYPE]}${url}`;
    } else {
      urlPath = `${strMap[process.env.ENV_TYPE]}${url}?${str}`;
    }
    return urlPath;
  },

  saveAppImage(strUrl) {
    let _this = this;
    uni.saveFile({
      tempFilePath: strUrl,
      success(data) {
        let savedFilePath = data.savedFilePath;
        // 在app端执行
        // #ifdef APP-PLUS
        let osname = plus.os.name;
        // 如果是安卓的话弹出提示
        if (osname == "Android") {
          uni.showToast({
            icon: "none",
            mask: true,
            title: "保存成功",
            duration: 1000,
          });
        }
        // #endif
        //ios手机直接打开文件，手动存储文件到手机，Android手机从根目录创建文件夹，保存文件并改名
        setTimeout(() => {
          //打开文档查看
          uni.openDocument({
            filePath: data.savedFilePath,
            success: function (ress) {
              console.log("成功打开文件");
            },
            fail() {
              console.log("打开文件失败");
            },
          });
        }, 1000);
      },
    });
  },
  //处理 元 和 万元
  unitConvert(num) {
    // 增强类型检查，确保可以转换为有效的数字，并处理 NaN
    let copyNum = num;
    if (isNaN((num = Number(num)))) {
      return "-";
    }
    if (copyNum < 0) {
      num = Number(num.toString().split("-")[1]);
      if (num < 10000) {
        return copyNum;
      }
    }
    const moneyUnits = ["", "万", "亿", "万亿"];
    const dividend = 10000;
    let currentNum = num;
    let currentUnit = moneyUnits[0];
    if (currentNum < 10000) {
      return currentNum === 0
        ? "0" + currentUnit
        : currentNum.toFixed(2) + currentUnit;
    }
    for (let i = 1; i < moneyUnits.length; i++) {
      currentUnit = moneyUnits[i];
      currentNum /= dividend;
      if (currentNum < 10000) {
        break;
      }
    }

    const result = {
      num: parseFloat(currentNum.toFixed(2)),
      unit: currentUnit,
    };
    if (copyNum < 0) {
      return "-" + result.num + result.unit;
    } else {
      return result.num + result.unit;
    }
  },

  async setWXConfig(option) {
    // console.log("jweixin", jweixin);
    let params = {
      url: encodeURIComponent(window.location.href.split("#")[0]),
    };
    const res = await shareToFriend(params);
    try {
      if (res) {
        jweixin.config({
          debug: false, // 开启调试模式
          appId: res.data.appId, // 必填，公众号的唯一标识
          timestamp: res.data.timestamp, // 必填，生成签名的时间戳
          nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
          signature: res.data.signature, // 必填，签名
          jsApiList: [
            "updateTimelineShareData",
            "updateAppMessageShareData",
            "hideMenuItems",
          ], // 必填，需要使用的JS接口列表
        });

        jweixin.ready(
          () => {
            jweixin.checkJsApi({
              jsApiList: [
                "updateTimelineShareData",
                "updateAppMessageShareData",
                'hideMenuItems'
              ],
              success: function (res) {
                JSON.stringify(res);
              },
            });
            jweixin.hideMenuItems({
              menuList: [
                "menuItem:exposeArticle",
                "menuItem:setFont",
                "menuItem:dayMode",
                "menuItem:nightMode",
                "menuItem:refresh",
                "menuItem:profile",
                "menuItem:addContact",
                "menuItem:share:qq",
                "menuItem:share:weiboApp",
                "menuItem:favorite",
                "menuItem:share:facebook",
                "menuItem:share:QZone",
                "menuItem:editTag",
                "menuItem:delete",
                "menuItem:copyUrl",
                "menuItem:originPage",
                "menuItem:readMode",
                "menuItem:openWithQQBrowser",
                "menuItem:openWithSafari",
                "menuItem:share:email",
                "menuItem:share:brand",
              ],
            });
            let shareData = {
              title: option.title ? option.title : "助融报告", //分享的标题
              desc: option.desc
                ? option.desc
                : "一键支持用户免费自查税信息，用户授权后免费自查，生成报告，简单方便。", //分享的描述
              link: option.link, //分享的链接
              imgUrl: `${
                location.origin + location.pathname
              }static/image/zhurongLogo.jpg`, // 分享图标
            };
            // console.log("shareData", shareData);
            jweixin.updateAppMessageShareData({
              ...shareData,
              success: (res) => {
                console.log("分享给朋友成功", res);
              },
              fail: (err) => {
                console.log("分享给朋友失败", err);
              },
            });
            //分享到朋友圈接口
            jweixin.updateTimelineShareData({
              ...shareData,
              success: (res) => {
                console.log("分享到朋友圈成功", res);
              },
              fail: (err) => {
                console.log("分享到朋友圈失败", err);
              },
            });
          },
          (err) => {
            console.log("err1", err);
          }
        );
      }
    } catch (error) {}
  },
  //单独处理违法数据结构
  setlawRegulationViolationVo(data) {
    // 定义字段映射关系
    const fieldConfig = [
      { key: 'actionName', name: '违法行为名称' },
      { key: 'infractionMeans', name: '税收违法手段' },
      { key: 'registerDate', name: '税务局登记日期' },
      { key: 'taxPeriodStart', name: '违法违章所属期起' },
      { key: 'taxPeriodEnd', name: '违法违章所属期止' },
      { key: 'processState', name: '处理状态' },
      { key: 'caseState', name: '案件状态' },
	    { key: 'illegalFact', name: '违法事实'},
	    { key: 'isSocialSecurityViolation',name: '是否社保违法'}
    ];
    const result = fieldConfig.map(field => {
      const baseObj = { month: field.name };
      data.forEach((_, index) => {
        baseObj[`value${index}`] = '';
      });
      return baseObj;
    });
    data.forEach((item, dataIndex) => {
      fieldConfig.forEach((field, fieldIndex) => {
        const valueKey = `value${dataIndex}`;
        result[fieldIndex][valueKey] = item[field.key] || '-';
      });
    });
    return result;
  },

   getCurrentRoute() {
    const pages = getCurrentPages()
    const page = pages[pages.length - 1]
    if (!page) return
    const route = { path: page.route, fullPath: page.$page?.fullPath, query: page.options }
    return route
}
};






